/**
 * 分类
 * 控制器
 */
const category_sql = require("../model/category");
const { Op } = require("sequelize");

module.exports = {
  // 获取列表
  category_list: async (req, res) => {
    try {
      const categorie_list = await category_sql.findAll();
      const categoryMap = new Map();
      // 按 ID 建立映射
      categorie_list.forEach((item) => {
        categoryMap.set(item.category_id, {
          category_id: item.category_id,
          parent_id: item.parent_id,
          category_name: item.category_name,
          children: [],
        });
      });
      // 构建树
      const rows = [];
      categorie_list.forEach((item) => {
        if (item.parent_id) {
          categoryMap.get(item.parent_id).children.push(categoryMap.get(item.category_id));
        } else {
          rows.push(categoryMap.get(item.category_id));
        }
      });
      res.json({ code: 1, message: "获取成功", data: rows });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 添加
  category_add: async (req, res) => {
    const { category_name, parent_id } = req.body;
    try {
      // 先查询是否存在
      if (await category_sql.findOne({ where: { category_name } })) {
        return res.json({ code: -1, message: "分类名称已存在" });
      }
      const information = await category_sql.create({ category_name, parent_id });
      if (!information) {
        return res.json({ code: -1, message: "添加失败" });
      }
      res.json({ code: 1, message: "添加成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 修改
  category_update: async (req, res) => {
    const { category_id, category_name, parent_id = null } = req.body;
    try {
      // 先查询是否存在
      const record = await category_sql.findByPk(category_id);
      if (!record) {
        return res.json({ code: -1, message: "分类不存在" });
      }
      const isExist = await category_sql.findOne({ where: { category_name, category_id: { [Op.ne]: category_id } } });
      if (isExist) {
        return res.json({ code: -1, message: "分类名称已存在" });
      }
      // 更新数据
      const updateData = {};
      if (category_name && category_name !== record.category_name) updateData.category_name = category_name;
      if (parent_id !== record.parent_id) updateData.parent_id = parent_id;

      if (Object.keys(updateData).length > 0) {
        const updateResult = await category_sql.update(updateData, { where: { category_id } });
        if (updateResult[0] <= 0) {
          return res.json({ code: -1, message: "更新失败" });
        }
      }
      res.json({ code: 1, message: "修改资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 删除
  category_delete: async (req, res) => {
    const { category_id } = req.query;
    try {
      // 先查询是否存在
      const record = await category_sql.findByPk(category_id);
      if (!record) {
        return res.json({ code: -1, message: "分类不存在" });
      }
      const row = await category_sql.destroy({ where: { category_id } });
      const rowChid = await category_sql.destroy({ where: { parent_id: category_id } });
      if (!row || !rowChid) {
        return res.json({ code: -1, message: "删除失败" });
      }
      res.json({ code: 1, message: "删除成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
};
